package com.ok.user.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ok.common.exception.CustomException;
import com.ok.common.utils.JwtUtils;
import com.ok.user.domain.po.OkAdmin;
import com.ok.user.mapper.OkAdminMapper;
import com.ok.user.service.IOkAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * <p>
 * 管理员 服务实现类
 * </p>
 *
 * @author lhw
 * @since 2024-05-06
 */
@Service
public class OkAdminServiceImpl extends ServiceImpl<OkAdminMapper, OkAdmin> implements IOkAdminService {

    @Override
    public String login(OkAdmin admin) {

        LambdaQueryWrapper<OkAdmin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OkAdmin::getUsername,admin.getUsername());

        OkAdmin okAdmin = this.getOne(queryWrapper);

        if (okAdmin == null){
            throw new CustomException("用户名未注册");
        }

        if (!okAdmin.getPassword().equals(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()))){
            throw new CustomException("密码错误");
        }

        HashMap<String, Object> map = new HashMap<>();

        map.put("adminId", okAdmin.getId());
        map.put("username", okAdmin.getUsername());
        map.put("password", okAdmin.getPassword());

        return JwtUtils.generateJwt(map);
    }
}
